import React, { Component } from 'react';
import style from './style.module.scss';
import { recommended, newPosts } from '../../Api';
import  Banner from '../../Components/Banner/Banner'
import Tabs from '../../Components/Tabs/Tab';

class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            posts: [],
            newPosts: {},
        };
    }

    componentDidMount() {
        recommended().then(res => {
            this.setState({
                posts: res.posts
            })
        })
        newPosts().then(res => {
            let news = {};
            res.posts.forEach(post => {
                let id = new Date(post.time).getDay();
                Array.isArray(news[id]) ? news[id] = [...news[id], post] : news[id] = [post];
            });
            function sortDate(date) {
                return (obj1, obj2) => obj1[date] < obj2[date] ? -1 : 1; 
            }
            for (const props in news) {
                let arr = news[props];
                news[props] = arr.sort(sortDate('time'));
            }
            this.setState({
                newPosts: news
            })
        })
    }

    render() {
        return(
            <div className={style.home}>
                <Banner data={this.state.posts}></Banner>
                <Tabs newPosts={this.state.newPosts}></Tabs>
            </div>
        )
    }
}

export default Home;